package cn.byapps.hw.schedule;

import cn.byapps.hw.dao.CronDao;
import cn.byapps.hw.dao.HomeworkFileDao;
import cn.byapps.hw.dao.HomeworkRequirementDao;
import cn.byapps.hw.entity.Cron;
import cn.byapps.hw.entity.HomeworkFile;
import cn.byapps.hw.entity.HomeworkRequirement;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
@Transactional
public class TaskCoudFileStore implements SchedulingConfigurer {
    @Value("${accessKey}")
    private String accessKey;// = "0o2MS26kFvP0vQPXIyk8TXdo6sIS1l3PRwES4Gwz";
    @Value("${secretKey}")
    private String secretKey;// = "WzafRljF_f_FEvv5TI_LaC7xTlbge9gPJTWQhrfW";
    @Value("${downloadPath}")
    private String downloadPath;
    @Value("${upload}")
    private String upload;
    @Value("${bucket}")
    private String bucket;// = "byapps";

    @Resource
    private HomeworkFileDao homeworkFileDao;
    @Resource
    private HomeworkRequirementDao homeworkRequirementDao;
    @Resource
    private CronDao cronDao;

    public static String cron;

    public void tranforeFile() {
        //构造一个带指定Region对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        // ...其他参数参考类注释
        System.out.println("List<HomeWorkFile> = tranforeFile");
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        if (upload == null || upload.equals("")) {
            upload = "upload";
        }
        // 将学生作业上传至七牛云
        /*Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("filePath", "%" + upload + "%");*/
        List<HomeworkFile> list = homeworkFileDao.findByFilePath("%" + upload + "%");
        System.out.println("List<HomeWorkFile> = " + list.size());

        int count = 0;
        for (HomeworkFile homeWorkFile : list) {

            String localFilePath = homeWorkFile.getFilePath();
            if (homeWorkFile.getMd5() == null || homeWorkFile.getMd5().equals(""))
                continue;
            if (count++ > 500)
                break;
            // 判断最否为同重复文件
           /* searchParams.put("filePath", "%" + downloadPath + "%");
            searchParams.put("md5", homeWorkFile.getMd5());*/
            List<HomeworkFile> list2 = homeworkFileDao.findByFilePathAndMd5("%" + downloadPath + "%", homeWorkFile.getMd5());
            if (list2.size() > 0) {
                homeWorkFile.setFilePath(list2.get(0).getFilePath());
                homeWorkFile.setComment("类同文件，" + homeWorkFile.getComment());
                homeworkFileDao.saveAndFlush(homeWorkFile);
                // 删除文件
                new File(localFilePath).delete();
                continue;
            }
            File file = new File(localFilePath);
            if (!file.exists()) {
                continue;
            }
            String key = localFilePath.substring(localFilePath.lastIndexOf(File.separator) + 1, localFilePath.length());
            try {
//				System.out.println(localFilePath);
                Response response = uploadManager.put(localFilePath, key, upToken);
                // 解析上传成功的结果
                 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//				System.out.println(putRet.key);
                homeWorkFile.setFilePath(downloadPath + "/" + key);
                //File file = new File(localFilePath);
//				homeWorkFile.setMd5(DecryptUtil.getMD5(file));
                homeworkFileDao.saveAndFlush(homeWorkFile);
                // 删除文件
                file.delete();
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    // ignore
                }
            }
        }
    }

    public void tranforeTeacherFile() {

        // Zone z = Zone.autoZone();
        // Configuration cfg = new Configuration(z);
         //构造一个带指定Region对象的配置类
         Configuration cfg = new Configuration(Region.huanan());
        // ...其他参数参考类注释
        System.out.println("List<MaterialRequirement> = tranforeTeacherFile");
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        if (upload == null || upload.equals("")) {
            upload = "upload";
        }
        // 将学生作业上传至七牛云
        /*Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("filePath", "%" + upload + "%");*/
        List<HomeworkRequirement> list = homeworkRequirementDao.findByFilePath("%" + upload + "%");
        System.out.println("List<HomeWorkFile> = " + list.size());

        for (HomeworkRequirement homeWorkFile : list) {

            String localFilePath = homeWorkFile.getFilePath();

            File file = new File(localFilePath);
            if (!file.exists()) {
                continue;
            }
            String key = localFilePath.substring(localFilePath.lastIndexOf(File.separator) + 1, localFilePath.length());
            try {
                System.out.println(localFilePath);
                Response response = uploadManager.put(localFilePath, key, upToken);
                // 解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                homeWorkFile.setFilePath(downloadPath + "/" + key);
                //File file = new File(localFilePath);
//				homeWorkFile.setMd5(DecryptUtil.getMD5(file));
                homeworkRequirementDao.saveAndFlush(homeWorkFile);
                // 删除文件
                file.delete();
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    // ignore
                }
            }
        }
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //项目部署时，会在这里执行一次，从数据库拿到cron表达式
        Optional<Cron> optionalCron = cronDao.findById(1);
        if (optionalCron != null && optionalCron.isPresent()) {
            cron = cronDao.findById(1).get().getCron();
        } else {
            cron = "0 0 5 * * ?";
            cronDao.saveAndFlush(new Cron(1, "0 0 5 * * ?"));
        }
        Runnable task = new Runnable() {
            @Override
            public void run() {
                //任务逻辑代码部分.
                tranforeFile();
                tranforeTeacherFile();
            }
        };
        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任务触发，可修改任务的执行周期.
                //每一次任务触发，都会执行这里的方法一次，重新获取下一次的执行时间
                if (optionalCron != null && optionalCron.isPresent()) {
                    cron = cronDao.findById(1).get().getCron();
                } else {
                    cron = "0 0 5 * * ?";
                    cronDao.saveAndFlush(new Cron(1, "0 0 5 * * ?"));
                }
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        };
        taskRegistrar.addTriggerTask(task, trigger);
    }
}

